<?php
namespace app\common\model;
use app\common\model\SubCenterRel as SubCenterRelModel;
use app\common\model\ViewGetSubCenter as ViewGetSubCenterModel;
use app\common\model\BookExtraDraw as BookExtraDrawModel;
use think\Validate;
use think\Db;
use think\facade\Log;

class SubCenter extends Common
{
    protected $rule = [
    ];
    protected $msg = [
    ];

    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        $list = $this->field($tableWhere['field'])->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);

        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;

        return $re;
    }
 
    /**
      * 添加科教中心
      * User:lhj
      * @param $data
      * @return array
      */
    public function addData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data'=> [],
            'token'  => \think\facade\Request::token('__ZlServer_Token__', 'sha1')
        ];

        $validate = new Validate($this->rule,$this->msg);
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            // 本部院、本专业只能归属于的一个科教中心
            $viewGetSubCenterModel = new ViewGetSubCenterModel();
            $info = $viewGetSubCenterModel->where(['dep_id'=>$data['dep_id'], 'specialty_id'=>$data['specialty_id']])->find();
            if($info){
                $info0 = $viewGetSubCenterModel->where(['dep_id'=>$data['dep_id'], 'centerName'=>$data['sub_center_name'], 'specialty_id'=>$data['specialty_id']])->find();
                if($info0){
                    $result['status'] = false;
                    $result['msg'] = '不能重复添加'; 
                    return $result;
                }
                $result['status'] = false;
                $result['msg'] = '本部/院下的该专业已归属于另一个科教中心'; 
                return $result;
            } 
            // 判断同名的科教中心是否已存在，获取科教中心ID
            $subCenterData = [];
            $subCenterData["name"] = $data["sub_center_name"];
            $subCenterData["deptId"] = $data["dep_id"];
            $subcenter_id = "";
            $subCenterInfo = $this->where(['name'=>$data['sub_center_name'], 'deptId'=>$data['dep_id']])->find();
            if($subCenterInfo){
                $subcenter_id = $subCenterInfo["id"];
            }
            else{
                $subcenter_id = $this->insertGetId($subCenterData); 
                if (!$subcenter_id) {
                    return error_code(10000);
                }
            }

            //设置部院、专业、科教中心关联
            $subCenterRelModel = new SubCenterRelModel();
            $subCenterRelData = [];
            $subCenterRelData["subcenter_id"] = $subcenter_id;
            $subCenterRelData["dep_id"] = $data["dep_id"];
            $subCenterRelData["specialty_id"] = $data["specialty_id"];

            if(!$subCenterRelModel->allowField(true)->save($subCenterRelData))
            {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            }
        }
        return $result;
    }

    /**
      * 编辑科教中心
      * User:lhj
      * @param $data
      * @return array
      */
    public function saveData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data'=> [],
            'token'  => \think\facade\Request::token('__ZlServer_Token__', 'sha1')
        ];

        $validate = new Validate($this->rule,$this->msg);
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            // 本部院下已存在名称相同的科教中心
            $viewGetSubCenterModel = new ViewGetSubCenterModel();
            $info = $viewGetSubCenterModel->where(['centerName'=>$data['sub_center_name'], 'deptName'=>$data['dep_name']])->find();
            if($info){
                $result['status'] = false;
                $result['msg'] = '本部/院下已存在名称相同的科教中心'; 
                return $result;
            }
            if (!$this->update(['name' => $data['sub_center_name']], ['id'=>$data['id']]))
            {
                $return['status'] = false;
                $return['msg']    = '保存失败'; 
            }
        }
        return $result;
    }

    /**
      * 删除科教中心
      * User:lhj
      * @param $data
      * @return array
      */
    public function delData($data)
    {
        $result = [
            'status' => true,
            'msg' => '删除成功',
            'data'=> [],
            'token'  => \think\facade\Request::token('__ZlServer_Token__', 'sha1')
        ];

        $validate = new Validate($this->rule,$this->msg);
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            // 非计划发书中有没有关联数据  
            $bookExtraDrawModel = new BookExtraDrawModel();
            $bookExtraDrawInfo = $bookExtraDrawModel->where(['sub_center_id'=>$data["id"]])->find();
            if($bookExtraDrawInfo){
                $result['status'] = false;
                $result['msg'] = '本科教中心存在发放记录，无法删除'; 
                return $result;
            }

            // 获取部院ID、专业ID
            $viewGetSubCenterModel = new ViewGetSubCenterModel();
            $info = $viewGetSubCenterModel->where(['deptName'=>$data['deptName'], 'centerName'=>$data['centerName'], 'specialtyName'=>$data['specialtyName']])->find();
            
            if(!$info){
                $result['status'] = false;
                $result['msg'] = '没查询到科教中心的相关信息，删除失败'; 
                return $result;
            }
            $subcenter_id = $data["id"];
            $dep_id = $info["dep_id"];
            $specialty_id = $info["specialty_id"];

            // 删除关联表数据
            $subCenterRelModel = new SubCenterRelModel();
            $subCenterRelModel->where(['subcenter_id' => $subcenter_id, 'dep_id' => $dep_id, 'specialty_id' => $specialty_id])->delete();

            // 如果关联表数据已空，删除本表数据
            $subCenterRelInfo = $subCenterRelModel->where(['subcenter_id'=>$subcenter_id])->find();
            if(!$subCenterRelInfo){
                $this->where(['id'=>$subcenter_id])->delete();
            }
        }
        return $result;
    }

    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];

        if(isset($post['deptId']) && $post['deptId'] != ""){
            $where[] = ['deptId', 'eq', $post['deptId']];
        }

        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['id ASC'];
        return $result;
    }

    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        return $list;
    }
}
